package com.corn.flink.lesson5;

import com.corn.flink.lesson4.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.evictors.CountEvictor;
import org.apache.flink.streaming.api.windowing.evictors.Evictor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.streaming.runtime.operators.windowing.TimestampedValue;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.Iterator;

/**
 * @author JimWu
 * @date 2023/3/16 15:23
 **/
public class EvictorDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<Event> ds = env.fromElements(
                new Event("add", 1000),
                new Event("delete", 2000),
                new Event("update", 3000),
                new Event("select", 5000),
                new Event("add", 6000),
                new Event("delete", 7000),
                new Event("select", 8000),
                new Event("select", 9000),
                new Event("select", 10000),
                new Event("select", 11000)
        );


        ds.assignTimestampsAndWatermarks(
                WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event element, long recordTimestamp) {
                                return element.timestamp;
                            }
                        }))
                .keyBy(data -> data.type)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .evictor(new Evictor<Event, TimeWindow>() {
                    // 移除前 在Window Function之前调用
                    @Override
                    public void evictBefore(Iterable<TimestampedValue<Event>> elements, int size, TimeWindow window, EvictorContext evictorContext) {
                        Iterator<TimestampedValue<Event>> it = elements.iterator();
                        while (it.hasNext()) {
                            TimestampedValue<Event> event = it.next();
                            if (event.getValue().type.equals("add")) {
                                it.remove();
                            }
                        }
                    }

                    // 移除后 在Window Function之后调用 默认情况下，预实现的移除器如CountEvictor 在处理完成数据之后流入下游的时候移除 都是在执行窗口函数（window fucntions）之前移除数据的
                    @Override
                    public void evictAfter(Iterable<TimestampedValue<Event>> elements, int size, TimeWindow window, EvictorContext evictorContext) {

                    }
                })
                .process(new ProcessWindowFunction<Event, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Event> elements, Collector<String> out) throws Exception {
                        long start = context.window().getStart();
                        long end = context.window().getEnd();
                        int times = 0;
                        for (Event element : elements) {
                            times++;
                        }
                        out.collect(new Timestamp(start) + " - " + new Timestamp(end) + " -> " + s + " : " + times);
                    }
                })
                .print();


        env.execute();
    }
}
